import React, { useEffect, useState } from 'react'
import { Settings } from '@/types'
import { useAtom } from 'jotai'
import { settingsAtom } from '@/atoms'
import { useTranslation } from 'react-i18next'
import { createPortal } from 'react-dom'
import { Button, Tabs, Tab, Dialog, DialogContent, DialogActions, DialogTitle } from '@mui/material'
import DisplaySettingTab from './DisplaySettingTab'
import DataSyncSettingTab from './DataSyncSettingTab'

let externalSetDialogOpen: (state: boolean) => void = () => {}

const SettingDialog: React.FC = () => {
  const { t } = useTranslation()
  const [open, setOpen] = useState(false)
  const [tab, setTab] = useState('display')
  const [settings, setSettings] = useAtom(settingsAtom)
  const [settingsEdit, setSettingsEdit] = React.useState<Settings>(settings)

  useEffect(() => {
    setSettingsEdit(settings)
    externalSetDialogOpen = setOpen
  }, [tab, settings])

  const onSave = () => {
    setSettings(settingsEdit)
    setOpen(false)
  }

  if (!open) return null

  return createPortal(
    <Dialog open onClose={() => setOpen(false)} fullWidth>
      <DialogTitle>{t('settings')}</DialogTitle>
      <DialogContent>
        <Tabs
          className="mb-1rem flex border-b border-b-gray-300 border-b-solid"
          value={tab}
          onChange={(_, value) => setTab(value)}
          scrollButtons
          allowScrollButtonsMobile
        >
          <Tab
            value="display"
            label={(
              <span className="inline-flex items-center justify-center gap-1">
                <div className="i-material-symbols:document-scanner-rounded text-1.1rem" />
                <span>{t('display')}</span>
              </span>
            )}
          />
          <Tab
            value="dataSync"
            label={(
              <span className="inline-flex items-center justify-center gap-1">
                <div className="i-material-symbols:display-settings text-1.1rem" />
                <span>{t('dataSync')}</span>
              </span>
            )}
          />
        </Tabs>
        {tab === 'display' && (
          <DisplaySettingTab
            settingsEdit={settingsEdit}
            setSettingsEdit={setSettingsEdit}
          />
        )}
        {tab === 'dataSync' && (
          <DataSyncSettingTab
            settingsEdit={settingsEdit}
            setSettingsEdit={setSettingsEdit}
          />
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={() => setOpen(false)}>{t('dialog cancel btn')}</Button>
        <Button onClick={onSave}>{t('dialog ok btn')}</Button>
      </DialogActions>
    </Dialog>,
    document.body,
  )
}

export const showSettingDialog = () => {
  externalSetDialogOpen(true)
}

export const hideSettingDialog = () => {
  externalSetDialogOpen(false)
}

export default SettingDialog
